import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import itertools
import matplotlib.animation as animation

# 数据：15个节点的简单图，这里使用固定的节点和边
nodes = list(range(15))
edges = [(0, 1), (0, 2), (0, 3), (1, 4), (2, 5), (3, 6), (4, 7), (5, 8), (6, 9), (7, 8), (8, 9),
         (10, 11), (10, 12), (10, 13), (11, 14), (12, 13), (13, 14),
         (0, 10), (1, 11), (2, 12), (3, 13), (4, 14), (5, 10), (6, 11), (7, 12), (8, 13), (9, 14)]

# 创建图对象
G = nx.Graph()
G.add_nodes_from(nodes)
G.add_edges_from(edges)


# 定义染色函数（简单的贪心染色）
def greedy_coloring(graph):
    colors = {}
    for node in graph.nodes():
        neighbor_colors = {colors[neighbor] for neighbor in graph.neighbors(node) if neighbor in colors}
        for color in ['red', 'yellow', 'blue', 'orange']:
            if color not in neighbor_colors:
                colors[node] = color
                break
    return colors


# 获取节点位置（这里随机生成位置）
pos = nx.spring_layout(G, seed=42)

# 染色节点
node_colors = ['white'] * len(nodes)


# 创建动画更新函数
def update(frame):
    if frame < len(nodes):
        # 染色节点
        node = nodes[frame]
        colors = greedy_coloring(G)
        node_colors[node] = colors[node]

        # 绘制图形
        color_map = [node_colors[node] if node_colors[node] != 'white' else 'white' for node in nodes]
        nx.draw(G, pos=pos, with_labels=True, node_color=color_map, edge_color='gray', node_size=800, font_size=12)
        plt.title(f'Coloring node {node} with color {node_colors[node]}')


# 设置动画参数
fig, ax = plt.subplots(figsize=(10, 8))  # 调整图形大小
ani = animation.FuncAnimation(fig, update, frames=len(nodes), interval=1000, repeat=False)

plt.show()
